import { watch } from 'vue';
import type { ConversationItem } from '@openim/client-sdk';
import { onUnload } from '@dcloudio/uni-app';
import { useThrottleFn } from '@vueuse/core';

import { IMSDK, IMMethods } from '@/utils/im';
import useConversationStore from '@/store/conversation';

export default function useConversationState() {
  const conversationStore = useConversationStore();

  // conversation state
  const checkConversationState = useThrottleFn(() => {
    if (!conversationStore.storeCurrentConversation.conversationID) return;
    if (conversationStore.storeCurrentConversation.unreadCount > 0) {
      IMSDK.asyncApi(
        IMMethods.MarkConversationMessageAsRead,
        IMSDK.uuid(),
        conversationStore.storeCurrentConversation.conversationID
      );
    }
  }, 1000);

  watch(
    () => conversationStore.storeCurrentConversation.conversationID,
    async newVal => {
      if (newVal) {
        checkConversationState();
      }
    },
    {
      immediate: true,
    }
  );

  watch(
    () => conversationStore.storeCurrentConversation.unreadCount,
    async newVal => {
      if (newVal) {
        checkConversationState();
      }
    },
    {
      immediate: true,
    }
  );

  onUnload(() => {
    checkConversationState();
    conversationStore.updateCurrentConversation({} as ConversationItem);
  });

  return {};
}
